package com.mauroleon.promotail.mobile;

import java.util.ArrayList;
import java.util.List;

import com.mauroleon.promotail.adapter.PromocionAdapter;
import com.mauroleon.promotail.canonical.Categoria;
import com.mauroleon.promotail.canonical.Promocion;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class PromocionList extends ListActivity {
	private static final int MENU_REPARSE = 0;
	
	private PromotailApp app;
	private List<Promocion> promociones;
	private ArrayAdapter<Categoria> spinnerAdapter;
	private ProgressDialog progressDialog;
	private Spinner categoriaSpinner;
	private PromocionAdapter promotionAdapter;
	private int actualCategoriaSeleccionado;
	private static final String TAG = "MyActivity";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lista_principal);

		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(false);
		progressDialog.setMessage(getString(R.string.loadingProgressDialog_text));

		app = (PromotailApp) getApplication();

		promociones = new ArrayList<Promocion>();
		promotionAdapter = new PromocionAdapter(this,promociones);

		setListAdapter(promotionAdapter);

		// get Sections list from application (parsing feed if necessary)
		if (app.getCategoriaList().isEmpty()) {
			if (app.connectionPresent()) {
				new ParseFeedTask().execute();
			} else {
				Toast.makeText(this,getString(R.string.loadingProgressDialog_text),
						Toast.LENGTH_LONG).show();
			}
		} else {
			//resetListItems(app.getCategoriaList().get(0).ge);
		}
		Log.v(TAG, "Inicio de Promo=");
		
		System.out.println("Inicio de Promo");
		// Spinner for choosing a Section
		categoriaSpinner = (Spinner) findViewById(R.id.promocion_spinner);
		spinnerAdapter = new ArrayAdapter<Categoria>(PromocionList.this,
				android.R.layout.simple_spinner_item, app.getCategoriaList());
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		categoriaSpinner.setAdapter(spinnerAdapter);
		categoriaSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long id) {
				if (actualCategoriaSeleccionado != position) {
					actualCategoriaSeleccionado = position;
					//resetListItems(app.getSectionList().get(position).getItems());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				// do nothing
			}
		});
	}

	private void resetListPromociones(List<Promocion> newPromociones) {
		promociones.clear();
		promociones.addAll(newPromociones);
		promotionAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position,long id) {
		//view.setBackgroundColor(android.R.color.background_light);
		//app.setCurrentItem(app.getCategoriaList().get(actualCategoriaSeleccionado).get.get(position));
		Intent dealDetails = new Intent(PromocionList.this, PromocionDetail.class);
		startActivity(dealDetails);
	}

	@Override
	public void onPause() {
		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, PromocionList.MENU_REPARSE, 0, R.string.promo_menu_consultar_promo);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_REPARSE:
			if (app.connectionPresent()) {
				new ParseFeedTask().execute();
			} else {
				Toast.makeText(this,
						getString(R.string.promo_msg_red_inhabilitada),
						Toast.LENGTH_LONG).show();
			}
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	// Use a custom Adapter to control the layout and views
	private class PromocionesAdapter extends ArrayAdapter<Promocion> {

		public PromocionesAdapter(List<Promocion> promociones) {
			super(PromocionList.this, R.layout.lista_item_promocion,
					promociones);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.lista_item_promocion,
						parent, false);
			}

			// use ViewHolder here to prevent multiple calls to findViewById (if
			// you have a large collection)
			ImageView image = (ImageView) convertView
					.findViewById(R.id.imagen_promo);
			image.setImageBitmap(BitmapFactory.decodeResource(getResources(),
					R.drawable.ic_launcher));

			TextView local = (TextView) convertView
					.findViewById(R.id.local_promo);
			TextView nombre = (TextView) convertView
					.findViewById(R.id.nombre_promo);
			TextView estado = (TextView) convertView
					.findViewById(R.id.estado_promo);

			Promocion promocion = getItem(position);

			if (promocion != null) {
				local.setText(promocion.getNombreCliente());
				Bitmap bitmap = app.getImageCache().get(
						promocion.getIdPromocion());
				if (bitmap != null) {
					image.setImageBitmap(bitmap);
				} else {
					// put item ID on image as TAG for use in task
					image.setTag(promocion.getIdPromocion());
					// separate thread/via task, for retrieving each image
					// (note that this is brittle as is, should stop all threads
					// in onPause)
					// new
					// RetrieveImageTask(image).execute(item.getSmallPicUrl());
				}
			}

			return convertView;
		}
	}

	// Use an AsyncTask<Params, Progress, Result> to easily perform tasks off of
	// the UI Thread
	private class ParseFeedTask extends AsyncTask<Void, Void, List<Categoria>> {

		@Override
		protected void onPreExecute() {
			progressDialog.show();
		}

		@Override
		protected List<Categoria> doInBackground(Void... args) {
			List<Categoria> categorias = app.getPromotailService().listarCategoria();
			return categorias;
		}

		@Override
		protected void onPostExecute(List<Categoria> taskCategoriaList) {
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (!taskCategoriaList.isEmpty()) {
				app.getCategoriaList().clear();
				app.getCategoriaList().addAll(taskCategoriaList);
				//resetListPromociones(taskCategoriaList.get(0).getPro);

				// for the "reparse" button, we also need to reset the spinner
				// data and put selection on 0 (Daily Deals)
				// (and since we don't have a member variable for the
				// spinnerAdapter's data, we just reset one by one)
				categoriaSpinner.setSelection(0);
				spinnerAdapter.clear();
				for (Categoria s : taskCategoriaList) {
					spinnerAdapter.add(s);
				}
			} else {
				Toast.makeText(PromocionList.this,getString(R.string.promo_msg_sin_datos),Toast.LENGTH_LONG).show();
			}
		}
	}

	private class RetrieveImageTask extends AsyncTask<String, Void, Bitmap> {
		private ImageView imageView;

		public RetrieveImageTask(ImageView imageView) {
			this.imageView = imageView;
		}

		@Override
		protected Bitmap doInBackground(String... args) {
			Bitmap bitmap = app.retrieveBitmap(args[0]);
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap bitmap) {
			if (bitmap != null) {
				imageView.setImageBitmap(bitmap);
				app.getImageCache().put((Long) imageView.getTag(), bitmap);
				imageView.setTag(null);
			}
		}
	}
}
